package com.ruoyi.utils.model.fastgpt;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import cn.hutool.json.JSONUtil;
import com.ruoyi.utils.model.fastgpt.vo.ChatMessage;
import com.ruoyi.utils.model.fastgpt.vo.FastGPTRequestBody;
import com.ruoyi.wwxkf.vo.WwxSyncMsg;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;

@Slf4j
public class FastGPTRequest {
    public static void main(String[] args) {
        WwxSyncMsg wwxSyncMsg = new WwxSyncMsg();
        wwxSyncMsg.setExternal_userid("as4dasd4as5d4as5d4a5s4d5sa4d5");
        requestAiMessage("你好啊", wwxSyncMsg);
    }

    public static String requestAiMessage(String content, WwxSyncMsg wwxSyncMsg) {
        HttpURLConnection connection = null;
        try {
            String externalUserid = wwxSyncMsg.getExternal_userid();
            URL url = new URL("https://cloud.fastgpt.cn/api/v1/chat/completions");
            connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Authorization", "Bearer fastgpt-qLeu49lIA7StxSNfbGGhWF3op02FqdjffB0nL79cBNEn2FARyWBG");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);
            String jsonInputString = buildJsonInputString(content, externalUserid);
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                return handleSuccessResponse(connection);
            } else {
                return handleErrorResponse(connection);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    private static String buildJsonInputString(String content, String externalUserid) {
        FastGPTRequestBody requestBody = new FastGPTRequestBody();
        requestBody.setChatId(externalUserid);
        requestBody.setStream(false);
        requestBody.setDetail(false);
        requestBody.setResponseChatItemId(externalUserid);

        Map<String, String> variables = new HashMap<>();
        variables.put("uid", externalUserid);
        variables.put("name", externalUserid);
        requestBody.setVariables(variables);

        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setRole("user");
        chatMessage.setContent(content);
        requestBody.setMessages(Collections.singletonList(chatMessage));

        return JSONUtil.toJsonStr(requestBody);
    }

    /**
     * @param connection
     * @return
     * @throws Exception
     */
    private static String handleSuccessResponse(HttpURLConnection connection) throws Exception {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"))) {
            StringBuilder response = new StringBuilder();
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
            JSONObject jsonResponse = new JSONObject(response.toString());
            String resultStr = jsonResponse
                    .getJSONArray("choices")
                    .getJSONObject(0)
                    .getJSONObject("message")
                    .getString("content");

            System.out.println("返回的内容: " + resultStr);
            return resultStr;
        }
    }

    /**
     * 处理错误响应
     *
     * @param connection
     * @return
     * @throws Exception
     */
    private static String handleErrorResponse(HttpURLConnection connection) throws Exception {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream(), "utf-8"))) {
            StringBuilder errorResponse = new StringBuilder();
            String errorLine;
            while ((errorLine = br.readLine()) != null) {
                errorResponse.append(errorLine.trim());
            }
            log.info("消息发送失败，失败内容{}", errorResponse.toString());
            return null;
        }
    }
}
